/*
virtual:虚拟属性
实时运行此属性的get函数
如：timeStr,先获取，10秒后再输出，显示的是当前时间，而不是10秒的时间
*/


const mongoose=require('mongoose');
const moment=require('moment');

mongoose.Promise=global.Promise;
mongoose.connect('mongodb://localhost:27017/test',{useMongoClient:true});

const VirtualSchema=new mongoose.Schema({
    name:String,
    time:Date
});

VirtualSchema.virtual('timeStr').get(function (){
    return moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
});

const Virtual=mongoose.model('Virtual',VirtualSchema);


let v={name:'name',time:new Date(),timeStr:'timeStr'};

new Virtual(v).save((err,ret)=>{
    console.log('save:',err,ret,moment(new Date()).format('YYYY-MM-DD HH:mm:ss'));
    ret.name='bbbb';
    ret.time='cccc';
    setTimeout(()=>{
        console.log(ret,ret.timeStr);
    },1000*3);
});